<template>
  <lay-layer
    :model-value="modelValue"
    @update:model-value="(value) => emit('update:modelValue', value)"
    :title="dialogTitle"
    :area="['800px', '600px']"
    :maxmin="true"
    :resize="true"
    @close="handleClose"
  >
    <div class="banner-dialog">
      <lay-form
        :model="formData"
        ref="formRef"
        :rules="formRules"
        label-width="100px"
        :disabled="props.mode === 'view'"
      >
        <lay-row :space="16">
          <lay-col :md="24">
            <lay-form-item label="标题" prop="title">
              <lay-input v-model="formData.title" placeholder="请输入轮播图标题" />
            </lay-form-item>
          </lay-col>
        </lay-row>

        <lay-row :space="16">
          <lay-col :md="24">
            <lay-form-item label="图片" prop="image">
              <ImageUpload
                v-model="formData.image"
                :multiple="false"
                :disabled="props.mode === 'view'"
                @upload-success="handleImageUploadSuccess"
                @upload-error="handleImageUploadError"
              />
              <div v-if="formData.image" class="current-image-info">
                <p class="image-url">当前图片: {{ formData.image }}</p>
              </div>
            </lay-form-item>
          </lay-col>
        </lay-row>

        <lay-row :space="16">
          <lay-col :md="24">
            <lay-form-item label="链接地址" prop="linkUrl">
              <lay-input v-model="formData.linkUrl" placeholder="请输入跳转链接地址" />
            </lay-form-item>
          </lay-col>
        </lay-row>

        <lay-row :space="16">
          <lay-col :md="12">
            <lay-form-item label="显示位置" prop="position">
              <lay-select v-model="formData.position" placeholder="请选择显示位置">
                <lay-select-option :value="1">首页顶部</lay-select-option>
                <lay-select-option :value="2">首页中部</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="12">
            <lay-form-item label="排序" prop="sortOrder">
              <lay-input-number 
                v-model="formData.sortOrder" 
                :min="0" 
                :max="999"
                placeholder="排序值"
              />
            </lay-form-item>
          </lay-col>
        </lay-row>



        <lay-row :space="16">
          <lay-col :md="12">
            <lay-form-item label="状态" prop="status">
              <lay-switch
                :model-value="formData.status === 1"
                @update:model-value="(value) => formData.status = value ? 1 : 0"
                :switch-text="['启用', '禁用']"
              />
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>

      <div class="dialog-footer">
        <lay-button @click="handleClose">取消</lay-button>
        <lay-button 
          v-if="props.mode !== 'view'" 
          type="primary" 
          @click="handleSubmit"
          :loading="submitting"
        >
          {{ props.mode === 'create' ? '创建' : '保存' }}
        </lay-button>
      </div>
    </div>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { layer } from '@layui/layui-vue'
import BannerApi from '@/api/module/banner'
import ImageUpload from '@/components/ImageUpload.vue'
import type { UploadResponse } from '@/api/module/upload'

// 定义接口
interface Banner {
  id?: number
  title: string
  image: string
  linkUrl: string
  sortOrder: number
  position: number
  status: number
  createdAt?: string
  updatedAt?: string
}

// 定义props
interface Props {
  modelValue: boolean
  mode: 'create' | 'edit' | 'view'
  bannerData?: Banner
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  mode: 'create',
  bannerData: undefined
})

// 定义emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref()
const submitting = ref(false)

// 表单数据
const formData = reactive<Banner>({
  title: '',
  image: '',
  linkUrl: '',
  position: 1,
  sortOrder: 0,
  status: 1
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传轮播图片', trigger: 'change' }
  ],
  position: [
    { 
      required: true, 
      message: '请选择显示位置', 
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
          callback(new Error('请选择显示位置'));
        } else {
          callback();
        }
      }
    }
  ],
  sortOrder: [
    { 
      required: true, 
      message: '请输入排序值', 
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
          callback(new Error('请输入排序值'));
        } else if (typeof value !== 'number' || value < 0) {
          callback(new Error('排序值必须是大于等于0的数字'));
        } else {
          callback();
        }
      }
    }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    create: '新增轮播图',
    edit: '编辑轮播图',
    view: '查看轮播图'
  }
  return titles[props.mode]
})

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  if (newVal && props.bannerData) {
    Object.assign(formData, props.bannerData)
  } else if (newVal && props.mode === 'create') {
    resetForm()
  }
}, { immediate: true })

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    title: '',
    image: '',
    linkUrl: '',
    position: 1,
    sortOrder: 0,
    status: 1
  })
  // 延迟清除验证，确保数据已经更新
  setTimeout(() => {
    formRef.value?.clearValidate()
  }, 0)
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
  resetForm()
}

// 图片上传成功处理
const handleImageUploadSuccess = (response: UploadResponse) => {
  formData.image = response.url
  layer.msg('图片上传成功', { icon: 1 })
}

// 图片上传失败处理
const handleImageUploadError = (error: any) => {
  console.error('图片上传失败:', error)
  layer.msg('图片上传失败', { icon: 2 })
}

// 提交表单
const handleSubmit = async () => {
  try {
    console.log('提交前的表单数据:', formData)
    console.log('position值:', formData.position, '类型:', typeof formData.position)
    console.log('sortOrder值:', formData.sortOrder, '类型:', typeof formData.sortOrder)
    
    await formRef.value?.validate()
    submitting.value = true
    
    if (props.mode === 'create') {
      // 创建轮播图
      await BannerApi.createBanner(formData)
      layer.msg('创建成功', { icon: 1 })
    } else if (props.mode === 'edit') {
      // 更新轮播图
      await BannerApi.updateBanner(formData.id!, formData)
      layer.msg('更新成功', { icon: 1 })
    }
    
    emit('success')
    handleClose()
  } catch (error) {
    console.error('操作失败:', error)
    layer.msg('操作失败', { icon: 2 })
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.banner-dialog {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}

.dialog-footer .lay-button {
  margin-left: 10px;
}

.current-image-info {
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  border-left: 3px solid #1890ff;
}

.image-url {
  margin: 0;
  font-size: 12px;
  color: #666;
  word-break: break-all;
}
</style>